﻿using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Identity;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys;
using SJ.Platform.EFCore.Model;
using System.Security.Claims;

namespace SJ.Platform.IdentityServer
{
    public class CustomProfileService : IProfileService
    {
        private readonly Sys_UserHandle sys_UserHandle;
        public CustomProfileService(SJDBContext dbContext)
        {
            sys_UserHandle = new Sys_UserHandle(dbContext);
        }
        /// <summary>
        /// 获取用户信息添加到返回结果中
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            if (context.RequestedClaimTypes.Any())
            {
                var user = await sys_UserHandle.GetEntityByIdAsync(context.Subject.GetSubjectId());

                if (user != null)
                {
                    var claims = new List<Claim>
                    {
                        new Claim("UserId", user.Id),
                        new Claim("RealName", user.RealName),
                        new Claim("OrgId",user.OrgId == null ? "" : user.OrgId),
                        new Claim("OrgName",user.OrgName == null ? "" : user.OrgName),
                        new Claim("Sex",user.Sex.ToString()),
                        new Claim ("Birthday",user.Birthday != null? user.Birthday.ToString() : ""),
                        new Claim("IsUsed",user.IsUsed.ToString())
                    };

                    context.IssuedClaims.AddRange(claims);
                }
            }
        }

        public Task IsActiveAsync(IsActiveContext context)
        {
            //var user = sys_UserHandle.GetEntityByIdAsync(context.Subject.GetSubjectId());
            context.IsActive = true;// user?.Status == 0;
            return Task.CompletedTask;
        }
    }
}